// pages/weather/weather.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
      now: "",
      hourly: "",
      cardCur: 0,
      swiperList: [{
        id: 0,
        type: 'image',
        scr: "/images/weather3.jpg"
      }, {
        id: 1,
        type: 'image',
        scr: "/images/weather4.jpg"
      }, {
        id: 2,
        type: 'image',
        scr: "/images/weather5.jpg"
      }, {
        id: 3,
        type: 'image',
        scr: "/images/weather6.jpg"
      }]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      this.towerSwiper('swiperList');
      // 初始化towerSwiper 传已有的数组名即可
      this.getLocation()
    },
    //选择定位
    selectLocation() {
      var that = this
      wx.chooseLocation({
        success(res) {
          //console.log(res)
          that.setData({
            location: res.longitude + "," + res.latitude
          })
          that.getWeather()
          that.getCityByLoaction()
        },
        fail() {
          wx.getLocation({
            type: 'gcj02',
            fail() {
              wx.showModal({
                title: '获取地图位置失败',
                content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
                success(mRes) {
                  if (mRes.confirm) {
                    wx.openSetting({
                      success: function (data) {
                        if (data.authSetting["scope.userLocation"] === true) {
                          that.selectLocation()
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'none',
                            duration: 1000
                          })
                        }
                      },
                      fail(err) {
                        console.log(err)
                        wx.showToast({
                          title: '唤起设置页失败，请手动打开',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    })
                  }
                }
              })
            }
          })

        }
      })
    },
    /**
     * 获取定位
     */
    getLocation() {
      var that = this
      wx.getLocation({
        type: 'gcj02',
        success(res) {
          that.setData({
            location: res.longitude + "," + res.latitude
          })
          that.getWeather()
          that.getCityByLoaction()
        },
        fail(err) {
          wx.showModal({
            title: '获取定位信息失败',
            content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
            success(mRes) {
              if (mRes.confirm) {
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] === true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      that.getLocation()
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                      that.setData({
                        location: "116.41,39.92"
                      })
                      that.getWeather()
                      that.getCityByLoaction()
                    }
                  },
                  fail(err) {
                    console.log(err)
                    wx.showToast({
                      title: '唤起设置页失败，请手动打开',
                      icon: 'none',
                      duration: 1000
                    })
                    that.setData({
                      location: "116.41,39.92"
                    })
                    that.getWeather()
                    that.getCityByLoaction()
                  }
                })
              } else if (mRes.cancel) {
                that.setData({
                  location: "116.41,39.92"
                })
                that.getWeather()
                that.getCityByLoaction()
              }
            }
          })
        }
      })
    },
    /**
     * 根据坐标获取城市信息
     */
    getCityByLoaction() {
      var that = this
      wx.request({
        url: 'https://geoapi.qweather.com/v2/city/lookup?key=' + "6a715e671a3d4fff8af065e441817ae8" + "&location=" + that.data.location,
        success(result) {
          var res = result.data
          if (res.code == "200") {
            var data = res.location[0]
            that.setData({
              City: data.adm2,
              County: data.name
            })
          } else {
            wx.showToast({
              title: '获取城市信息失败',
              icon: 'none'
            })
          }

        }
      })
    },
    /**
     * 获取天气
     */
    getWeather() {
      var that = this
      wx.request({
        url: 'https://devapi.qweather.com/v7/weather/now?key=' + "6a715e671a3d4fff8af065e441817ae8" + "&location=" + that.data.location,
        success(result) {
          var res = result.data
          //console.log(res)
          that.setData({
            now: res.now
          })
        }
      })
      wx.request({
        url: 'https://devapi.qweather.com/v7/weather/24h?key=' + "6a715e671a3d4fff8af065e441817ae8" + "&location=" + that.data.location,
        success(result) {
          var res = result.data
          //console.log(res)
          res.hourly.forEach(function (item) {
            item.time = that.formatTime(new Date(item.fxTime)).hourly
          })
          that.setData({
            hourly: res.hourly
          })
        }
      })
    },
    // 格式时间
    formatTime(date) {
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()
      const weekArray = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
      const isToday = date.setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0)
      return {
        hourly: [hour, minute].map(this.formatNumber).join(":"),
        daily: [month, day].map(this.formatNumber).join("-"),
        dailyToString: isToday ? "今天" : weekArray[date.getDay()]
      }
    },
    // 补零
    formatNumber(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    },
    DotStyle(e) {
      this.setData({
        DotStyle: e.detail.value
      })
    },
    // cardSwiper
    cardSwiper(e) {
      this.setData({
        cardCur: e.detail.current
      })
    },
    // towerSwiper
    // 初始化towerSwiper
    towerSwiper(name) {
      let list = this.data[name];
      for (let i = 0; i < list.length; i++) {
        list[i].zIndex = parseInt(list.length / 2) + 1 - Math.abs(i - parseInt(list.length / 2))
        list[i].mLeft = i - parseInt(list.length / 2)
      }
      this.setData({
        swiperList: list
      })
    },
    // towerSwiper触摸开始
    towerStart(e) {
      this.setData({
        towerStart: e.touches[0].pageX
      })
    },
    // towerSwiper计算方向
    towerMove(e) {
      this.setData({
        direction: e.touches[0].pageX - this.data.towerStart > 0 ? 'right' : 'left'
      })
    },
    // towerSwiper计算滚动
    towerEnd(e) {
      let direction = this.data.direction;
      let list = this.data.swiperList;
      if (direction == 'right') {
        let mLeft = list[0].mLeft;
        let zIndex = list[0].zIndex;
        for (let i = 1; i < list.length; i++) {
          list[i - 1].mLeft = list[i].mLeft
          list[i - 1].zIndex = list[i].zIndex
        }
        list[list.length - 1].mLeft = mLeft;
        list[list.length - 1].zIndex = zIndex;
        this.setData({
          swiperList: list
        })
      } else {
        let mLeft = list[list.length - 1].mLeft;
        let zIndex = list[list.length - 1].zIndex;
        for (let i = list.length - 1; i > 0; i--) {
          list[i].mLeft = list[i - 1].mLeft
          list[i].zIndex = list[i - 1].zIndex
        }
        list[0].mLeft = mLeft;
        list[0].zIndex = zIndex;
        this.setData({
          swiperList: list
        })
      }
    },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})